package service

import (
	"context"
	"github.com/gin-gonic/gin"
	"im/helper"
	"im/models"
	"log"
	"net/http"
	"os"
	"time"
)

func Register(ctx *gin.Context) {
	// 获取变量
	captchaCode := ctx.PostForm("captchaCode")
	email := ctx.PostForm("email")
	accout := ctx.PostForm("account")
	password := ctx.PostForm("password")
	if captchaCode == "" || email == "" || password == "" || accout == "" {
		log.Println("参数错误！")
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "参数不正确",
		})
		return
	}
	count, err := models.GetUserBasicCountByAccount(accout)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		log.Fatalln(err.Error())
		return
	}
	if count > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "账号已注册",
		})
		return
	}
	// 验证码校验
	RegisterPrefix := os.Getenv("REGISTERPREFIX")
	result, err := models.RDB.Get(context.Background(), RegisterPrefix+email).Result()
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}
	if result != captchaCode {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "验证码不正确",
		})
		return
	}
	ub := &models.UserBasic{
		Identity:  helper.GetUUID(),
		Account:   accout,
		Password:  helper.GetMd5(password),
		Email:     email,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	err = models.InsertOneUserBasic(ub)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "插入失败：" + err.Error(),
		})
		return
	}
	token, err := helper.GenerateToken(ub.Identity, ub.Email)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "获取token错误" + err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": gin.H{
			"token": token,
		},
	})
}

// 发送验证码
func SendCode(ctx *gin.Context) {
	ExpireTime := 300
	email := ctx.PostForm("email")
	if email == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "邮箱不能为空",
		})
		return
	}
	count, _ := models.GetUserBasicCountByEmail(email)
	if count > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "该邮箱已被注册",
		})
		return
	}
	captchaCode, _ := helper.GenerateCaptchaCode(8)
	err := helper.SendCaptchaCode(email, captchaCode)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code":  -1,
			"email": email,
			"msg":   "发送验证码失败-" + err.Error(),
		})
		return
	}
	RegisterPrefix := os.Getenv("REGISTERPREFIX")
	err = models.RDB.Set(ctx, RegisterPrefix+email, captchaCode, time.Second*time.Duration(ExpireTime)).Err()
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "插入redisDB失败：" + err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "已发送验证码，请在五分钟内完成验证" + captchaCode,
	})
}

// 用户登陆
func Login(c *gin.Context) {
	account := c.PostForm("account")
	password := c.PostForm("password")
	if account == "" || password == "" {
		c.JSON(http.StatusForbidden, gin.H{
			"code": -1,
			"msg":  "用户名或密码不能为空",
		})
		return
	}
	ub, err := models.GetUserBasicByAccountPassword(account, helper.GetMd5(password))
	if err != nil {
		c.JSON(http.StatusForbidden, gin.H{
			"code": -1,
			"msg":  "用户名或密码错误:" + err.Error(),
		})
		return
	}
	token, err := helper.GenerateToken(ub.Identity, ub.Email)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "系统错误" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "Success",
		"data": gin.H{
			"token": token,
		},
	})
}

/*
用户操作
*/
// 添加好友
func UserAdd(c *gin.Context) {
	account := c.PostForm("account")
	if account == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "账号为空",
		})
		return
	}
	ub, err := models.GetUserBasicByAccount(account)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "获取用户信息失败：:" + err.Error(),
		})
		return
	}
	uc := c.MustGet("user_claims").(*helper.UserClaims)
	if models.JudegeUserIsFriend(ub.Identity, uc.Identity) {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "互为好友，无需添加",
		})
		return
	}
	rb := &models.RoomBasic{
		RoomIdentity: helper.GetUUID(),
		UserIdentity: ub.Identity,
		CreatedAt:    time.Now().Unix(),
		UpdatedAt:    time.Now().Unix(),
	}
	if err = models.InsertOneRoomBasic(rb); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "数据库异常：" + err.Error(),
		})
		return
	}
	ur1 := &models.UserRoom{
		UserIdentity: ub.Identity,
		RoomIdentity: rb.RoomIdentity,
		RoomType:     1,
		CreatedAt:    time.Now().Unix(),
		UpdateAt:     time.Now().Unix(),
	}
	ur2 := &models.UserRoom{
		UserIdentity: uc.Identity,
		RoomIdentity: rb.RoomIdentity,
		RoomType:     1,
		CreatedAt:    time.Now().Unix(),
		UpdateAt:     time.Now().Unix(),
	}
	userRooms := []*models.UserRoom{ur1, ur2}
	if err = models.InsertManyUserRoom(userRooms); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "数据库错误：" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "Success",
	})
}

func UserDelete(c *gin.Context) {
	identity := c.Query("identity")
	if identity == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "参数不能为空",
		})
		return
	}
	uc := c.MustGet("user_claims").(*helper.UserClaims)
	roomIdentity, err := models.GetUserRoomIdentity(identity, uc.Identity)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "获取房间ID失败：" + err.Error(),
		})
		return
	}
	err = models.DeleteUserRoom(roomIdentity)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "删除用户失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "Success",
	})
}

/*
查询用户
*/
// 查询用户详细数据
func UserDetails(c *gin.Context) {
	u, _ := c.Get("user_claims")
	uc := u.(*helper.UserClaims)
	userBasic, err := models.GetUserBasicByIdentity(uc.Identity)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "查询用户失败：" + err.Error(),
		})
		log.Println(err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "Success",
		"data": userBasic,
	})
}

// 查询用户
func UserQuery(c *gin.Context) {
	account := c.Query("account")
	if account == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "账号为空",
		})
		return
	}
	ub, err := models.GetUserBasicByAccount(account)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "查询失败：" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "Success",
		"data": gin.H{
			"account": ub.Account,
			"email":   ub.Email,
		},
	})
}
